import { useEffect, useState } from "react";
import Header from "@/components/Header";
import {
  Input,
  Select,
  Table,
  Button,
  TableColumnsType,
  Spin,
  Modal,
  Form,
  Tag,
  message,
  Popconfirm,
} from "antd";
import "./css/store.scss";
import { storeData, addStaff } from "./interface/interfaces";
import axios from "axios";
const { Search } = Input;

export default function StaffManage() {
  const [spinning] = useState<boolean>(false);
  const [open, setOpen] = useState(false); //添加框
  const [list, setList] = useState([]); //列表
  const [selectOption, setSelectOption] = useState([]); //门店下拉框
  const [optionAdd, setOptionAdd] = useState([]); //添加岗位下拉框
  const [title, setTit] = useState(""); //标题
  const [addEdit] = Form.useForm();
  const columns: TableColumnsType<storeData> = [
    {
      title: "编号",
      width: 100,
      dataIndex: "id",
      key: "id",
      defaultSortOrder: "ascend", //默认升序
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: "姓名",
      width: 100,
      dataIndex: "name",
      key: "name",
    },
    {
      title: "所在门店",
      dataIndex: "storeName",
      key: "storeName",
      width: 150,
    },
    {
      title: "联系电话",
      dataIndex: "tell",
      key: "tell",
      width: 150,
    },
    {
      title: "岗位",
      dataIndex: "postName",
      key: "postName",
      width: 150,
    },
    {
      title: "人员状态",
      dataIndex: "status",
      key: "status",
      width: 150,
      render: (record) => {
        return (
          <Tag color={record == "true" ? "green" : "red"}>
            {record === "true" ? "在职" : "离职"}
          </Tag>
        );
      },
    },
    {
      title: "操作",
      key: "operation",
      width: 150,
      render: (record) => {
        return (
          <div>
            <Button type="link" onClick={() => editForm(record)}>
              修改信息
            </Button>
            <Popconfirm
              title="删除该条数据"
              description="是否要删除选中数据？"
              okText="Yes"
              cancelText="No"
              onConfirm={() => deleteStore(record.id)}
            >
              {" "}
              <Button type="link">删除门店</Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];
  useEffect(() => {
    getList();
    getStore();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 获取列表
  async function getList() {
    getPost();
    const { data } = await axios.get("http://127.0.0.1:3100/zsl/getStaffList");
    if (data.code === 200) {
      setList(data.data);
    }
  }

  // 获取门店下拉框门店名称
  async function getStore() {
    const { data } = await axios.get("http://127.0.0.1:3100/zsl/getStoreName");
    const arr = [];
    data.data.forEach((item: storeData) => {
      arr.push({ value: item.id, label: item.name });
    });
    arr.unshift({ value: "全部", label: "全部" });
    setSelectOption(arr);
  }
  // 获取岗位
  async function getPost() {
    const { data } = await axios.get("http://127.0.0.1:3100/zsl/getKeyPost");
    setOptionAdd(data.data);
  }

  // 门店名称---搜索
  const onChangeSelect = async (value: string | number) => {
    console.log(value);
    if (value === "全部") {
      getList();
    } else {
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/getStoreStaff?id=" + value
      );
      setList(data.data);
    }
  };
  // 员工名称--搜索
  const onSearch = async (value: string) => {
    if (value !== "") {
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/getStaffList?name=" + value
      );
      console.log(data, "获取列表数据");
      if (data.code === 200) {
        setList(data.data);
      }
    } else {
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/getStaffList"
      );
      console.log(data, "获取列表数据");
      if (data.code === 200) {
        setList(data.data);
      }
    }
  };

  // 添加表单
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onFinish = async (values: addStaff) => {
    if (values.id) {
      const { data } = await axios.post(
        "http://127.0.0.1:3100/zsl/editStaff",
        values
      );
      if (data.code === 200) {
        message.success("修改成功");
        setOpen(false);
        getList();
      }
    } else {
      const { data } = await axios.post(
        "http://127.0.0.1:3100/zsl/addStaff",
        values
      );
      if (data.code === 200) {
        message.success("添加成功");
        setOpen(false);
        getList();
      }
    }
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const editForm = (record: addStaff) => {
    setOpen(true);
    setTit("修改员工");
    addEdit.setFieldsValue(record);
    console.log(addEdit);
  };
  // 关闭的时候清空表单
  const cleanForm = () => {
    setOpen(false);
    addEdit.resetFields();
    setTit("");
  };
  // 删除员工
  const deleteStore = async (id: number) => {
    const { data } = await axios.get(
      "http://127.0.0.1:3100/zsl/deleteStaff?id=" + id
    );
    if (data.code === 200) {
      message.success(data.msg);
      getList();
    }
  };

  return (
    <div className="storeBigBox">
      <Spin spinning={spinning}>
        <Header title="员工管理" />
        <div className="searchBox">
          <div>
            <span
              style={{
                marginTop: "5px",
                display: "inline-block",
                marginRight: "5px",
              }}
            >
              员工姓名
            </span>
            <Search
              placeholder="请输入内容"
              onSearch={onSearch}
              style={{
                width: 200,
              }}
            />
          </div>
          <div style={{ marginLeft: "50PX" }}>
            <span
              style={{
                marginTop: "5px",
                display: "inline-block",
                marginRight: "5px",
              }}
            >
              门店名称
            </span>
            <Select
              showSearch
              placeholder="请选择状态"
              optionFilterProp="children"
              onChange={onChangeSelect}
              options={selectOption}
            />
          </div>
        </div>
        <div className="storeContent">
          <Button
            type="primary"
            style={{ float: "right", marginBottom: "10px" }}
            onClick={() => setOpen(true)}
          >
            添加员工
          </Button>
          <Table
            columns={columns}
            dataSource={list}
            scroll={{ y: 350 }}
            pagination={{
              defaultPageSize: 3, //默认每页显示条数
              defaultCurrent: 1, //默认当前页数第二页
              pageSizeOptions: ["3", "5", "10"], //每页显示多少条
              locale: {
                items_per_page: "条/页",
              },
            }}
          />
        </div>
        {/* 添加框 */}
        <Modal
          title={title !== "" ? "编辑员工" : "添加员工"}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
          open={open}
          onCancel={() => cleanForm()}
        >
          <Form
            name="basic"
            onFinish={onFinish}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 10 }}
            form={addEdit}
          >
            {title !== "" ? (
              <Form.Item label="ID" name="id">
                <Input disabled />
              </Form.Item>
            ) : (
              ""
            )}
            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: "姓名不能为空!" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="联系方式"
              name="tell"
              rules={[
                {
                  required: true,
                  message: "联系方式不能为空",
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: "请输入正确手机号",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="所属门店"
              name="sid"
              rules={[{ required: true, message: "门店不能为空" }]}
            >
              <Select
                placeholder="请选择状态"
                optionFilterProp="children"
                options={selectOption}
              />
            </Form.Item>
            <Form.Item label="岗位" name="kid">
              <Select
                placeholder="请选择岗位"
                // style={{ flex: 1 }}
                options={optionAdd}
              />
            </Form.Item>
            <Form.Item wrapperCol={{ span: 8, offset: 8 }}>
              <Button type="primary" htmlType="submit">
                {title !== "" ? "编辑" : "添加"}
              </Button>
              <Button
                type="primary"
                onClick={() => setOpen(false)}
                style={{ marginLeft: "10px" }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Spin>
    </div>
  );
}
